package sso.resource.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.AccessDeniedHandler;
import sso.resource.utils.WebUtils;

import java.util.HashMap;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
            //1.关闭跨域攻击
            http.csrf().disable();
            //2.设置拒绝处理器(不允许访问资源时,应该给出什么反馈)
            http.exceptionHandling()
                    .accessDeniedHandler(accessDeniedHandler());
            //3.资源访问(所有资源在本项目中的访问不进行认证)
            http.authorizeRequests().anyRequest().permitAll();
    }
    //没有权限时执行此方法
    public AccessDeniedHandler accessDeniedHandler(){
        return (request, response,  e) ->{
            HashMap<String, Object> map = new HashMap<>();
            map.put("state",403);
            map.put("message","没有访问权限,请联系管理员");
            WebUtils.writeJsonToClient(response,map);
        };
    }
}
